const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { Unauthorized } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

module.exports = async (req, res, next) => {
  try {
    const token = req.headers.token || req.query.token;
    if (!token) {
      throw new Unauthorized('无权限访问');
    }
    const decoded = jwt.verify(token, process.env.SECRET);
    const { userId } = decoded;
    // const user = await User.findByPk(userId);
    // if (!user) {
    //     throw new Unauthorized('用户不存在')
    // }
    // if (user.role !== 100) {
    //     throw new Unauthorized('没有权限')
    // }
    req.userId = userId;
    next();
  } catch (error) {
    failure(res, error);
  }
};
